<template>
  <div :class="['modal', {fade: fade}]" data-backdrop="static" data-disable="false" data-keyboard="true" tabindex="-1">
    <div :class="['modal-dialog', size]">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
          <h4 class="modal-title text-center text-primary"><span>{{ title }}</span></h4>
        </div>
        <div class="modal-body">
          <form class="form-inline" autocomplete="off" spellcheck="false">
            <div class="form-group form-group-sm">
              <label>搜索</label>
              <input type="text" class="form-control" placeholder="关键字" v-model.trim="q" @keydown.enter.prevent ref="q">
            </div>
            <span class="hidden-xs">&nbsp;&nbsp;</span>
            <div class="form-group form-group-sm">
              <label>轮播间隔(秒)</label>
              <el-input-number size="mini" placeholder="轮播间隔 (秒)" v-model="interval" :min="10" label="轮播间隔"
                               controls-position="right"></el-input-number>
            </div>
            <span class="hidden-xs">&nbsp;&nbsp;</span>
            <div class="form-group form-group-sm">
              <div class="checkbox">
                <el-checkbox style="margin-top:-5px;padding-left:0;" size="small" v-model.trim="related" name="Related">
                  只看已选({{ localChannelsAll.length }})
                </el-checkbox>
              </div>
            </div>
          </form>
          <br>
          <el-table :data="related ? localChannels:channels" stripe @sort-change="sortChange" @select="select"
                    @select-all="selectAll" :max-height="500" @row-click="rowClick" :row-style="rowStyle"
                    ref="channelTable" v-loading="loading" element-loading-text="加载中...">
            <el-table-column type="selection" width="55" fixed :selectable="selectable"></el-table-column>
            <el-table-column prop="DeviceID" label="设备国标编号" min-width="200" show-overflow-tooltip sortable="custom"
                             :fixed="!isMobile()"></el-table-column>
            <el-table-column prop="ID" label="通道国标编号" min-width="200" show-overflow-tooltip sortable="custom"
                             :fixed="!isMobile()"></el-table-column>
            <el-table-column prop="Name" label="通道名称" min-width="120" :formatter="formatName"
                             show-overflow-tooltip></el-table-column>
            <el-table-column prop="Status" label="在线状态" min-width="100">
              <template slot-scope="props">
                <span v-if="props.row.SubCount > 0">-</span>
                <span v-else-if="props.row.Status == 'ON'" class="text-success">在线</span>
                <span v-else>离线</span>
              </template>
            </el-table-column>
            <el-table-column prop="SubCount" label="子节点数" min-width="100" v-if="hasAnyRole(serverInfo, userInfo, '管理员')"
                             sortable="custom"></el-table-column>
            <el-table-column prop="Manufacturer" label="厂家" min-width="120" :formatter="formatManufacturer"
                             show-overflow-tooltip></el-table-column>
          </el-table>
          <el-pagination v-if="total > 0 && !related"
                         :layout="index == -1 ? 'total,prev,pager,next,sizes':'total,prev,pager,next'"
                         :pageSizes="[10, 20, 50, 100, 200]" :pager-count="isMobile() ? 3 : 5" class="pull-right"
                         :total="total" :page-size.sync="pageSize" :current-page.sync="currentPage"></el-pagination>
          <div class="clearfix"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" @click.prevent="startLoopPlay"><i class="fa fa-play"></i> 开始轮巡播放
          </button>
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
  </div>
</template>

<script>
import _ from 'lodash'
import $ from 'jquery'
import "jquery-ui/ui/widgets/draggable";
import {mapState} from "vuex"

export default {
  props: {
    title: {
      default: ''
    },
    size: {
      type: String,
      default: 'modal-lg'
    },
    fade: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      q: "",
      total: 0,
      pageSize: 10,
      currentPage: 1,
      sort: "",
      order: "",
      loading: false,
      channels: [],
      index: 0,
      localData: {
        interval: 10,
        rows: {},
      },
      related: false,
      localChannels: [],
      localChannelsAll: [],
      interval: 10,
    };
  },
  computed: {
    ...mapState(["userInfo", "serverInfo"])
  },
  watch: {
    q: function (newVal, oldVal) {
      this.doDelaySearch();
    },
    currentPage: function (newVal, oldVal) {
      this.doSearch(newVal);
    },
    pageSize: function (newVal, oldVal) {
      this.doSearch();
    },
    related: function (newVal, oldVal) {
      if (newVal) {
        this.loadLocalChannels();
      } else {
        this.doSearch();
      }
    },
    interval: function (newVal, oldVal) {
      this.localData.interval = newVal;
      this.setLocalData(true);
    },
  },
  mounted() {
    this.loadLocalData();
    $(this.$el).find('.modal-content').draggable({
      handle: '.modal-header',
      cancel: ".modal-title span",
      addClasses: false,
      containment: 'document',
      delay: 100,
      opacity: 0.5
    });
    $(this.$el).on("shown.bs.modal", () => {
      this.$emit("show");
    }).on("hidden.bs.modal", () => {
      this.errors.clear();
      // this.reset();
      this.$emit("hide");
    })
  },
  methods: {
    sortChange(data) {
      this.sort = data.prop;
      this.order = data.order == "ascending" ? "asc" : "desc";
      this.getChannels();
    },
    doSearch(page = 1) {
      this.currentPage = page;
      if (this.related) {
        this.loadLocalChannels();
      } else {
        this.getChannels();
      }
    },
    doDelaySearch: _.debounce(function () {
      this.doSearch();
    }, 500),
    formatName(row, col, cell) {
      return row.CustomName || row.Name || "-";
    },
    formatManufacturer(row, col, cell) {
      if (cell) return cell;
      return "-";
    },
    getChannels() {
      this.loading = true;
      $.get(this.$baseUrl.http + "/api/v1/device/channellist", {
        q: this.q,
        start: (this.currentPage - 1) * this.pageSize,
        limit: this.pageSize,
        channel_type: "device",
        online: "true",
        sort: this.sort,
        order: this.order
      }).then(ret => {
        this.total = ret.ChannelCount;
        this.channels = ret.ChannelList || [];
        this.$nextTick(() => {
          this.channels.forEach(row => {
            if (this.localData.rows[row.DeviceID + "_" + row.ID]) {
              this.localData.rows[row.DeviceID + "_" + row.ID] = row;
              this.$refs["channelTable"].toggleRowSelection(row);
            }
          })
          this.setLocalData(false);
        })
      }).always(() => {
        this.loading = false;
      });
    },
    rowClick(row, event, column) {
      if (!row) {
        return
      }
      if (this.localData.rows[row.DeviceID + "_" + row.ID]) {
        delete this.localData.rows[row.DeviceID + "_" + row.ID];
      } else {
        this.localData.rows[row.DeviceID + "_" + row.ID] = row;
      }
      this.$refs["channelTable"].toggleRowSelection(row);
      this.setLocalData(false);
    },
    rowStyle({
               row,
               rowIndex
             }) {
      if (row.Online == 1) {
        return "cursor:pointer";
      }
      return "";
    },
    reset() {
      this.index = 0;
      this.channels = [];
      this.q = "";
      this.currentPage = 1;
      this.pageSize = 10;
    },
    show(index) {
      this.index = index;
      $(this.$el).modal("show");
      if (this.related) {
        this.loadLocalData()
      } else {
        this.getChannels();
      }
    },
    hide() {
      $(this.$el).modal("hide");
    },
    selectable(row, index) {
      return true;
    },
    select(selection, row) {
      var r = this.localData.rows[row.DeviceID + "_" + row.ID] || "";
      var idx = selection.indexOf(row);
      if (idx >= 0) {
        if (!r) {
          this.localData.rows[row.DeviceID + "_" + row.ID] = row;
        }
      } else {
        if (r) {
          delete this.localData.rows[row.DeviceID + "_" + row.ID];
        }
      }
      this.setLocalData();
    },
    selectAll(selection) {
      var keys = [];
      var baks = {};
      if (selection.length) {
        this.selection = selection;
        for (var row of selection) {
          var r = this.localData.rows[row.DeviceID + "_" + row.ID] || "";
          if (!r) {
            this.localData.rows[row.DeviceID + "_" + row.ID] = row;
          }
        }
      } else {
        for (var row of this.channels) {
          var r = this.localData.rows[row.DeviceID + "_" + row.ID] || "";
          if (r) {
            delete this.localData.rows[row.DeviceID + "_" + row.ID];
          }
        }
      }
      this.setLocalData();
    },
    setLocalData(updateSet) {
      localStorage['livegbsscreen_loopplay'] = JSON.stringify(this.localData);
      if (!updateSet) {
        this.loadLocalChannels();
      }
    },
    loadLocalData() {
      if (localStorage['livegbsscreen_loopplay']) {
        this.localData = JSON.parse(localStorage['livegbsscreen_loopplay']);
        this.interval = this.localData.interval;
        this.loadLocalChannels();
      }
    },
    loadLocalChannels() {
      var localRows = [];
      var localRowsAll = [];
      for (var key in this.localData.rows) {
        var r = this.localData.rows[key];
        localRowsAll.push(r);
        if (this.q == "") {
          localRows.push(r);
        } else {
          if ((r.Name.indexOf(this.q) != -1 || (r.Channel + "").indexOf(this.q) != -1)) {
            localRows.push(r);
          }
        }
      }
      this.localChannelsAll = localRowsAll;
      this.localChannels = localRows;
      if (this.related) {
        this.$nextTick(() => {
          this.localChannels.forEach(row => {
            this.$refs["channelTable"].toggleRowSelection(row);
          })
        })
      }
    },
    startLoopPlay() {
      if (this.localChannels.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择需要轮巡播放的通道"
        })
        return
      }
      this.$emit("loopPlay", this.localChannels, this.interval);
      this.hide();
    },
  }
};
</script>

<style lang="less" scoped>
label.el-switch {
  margin-bottom: -10px;
}
</style>
